/**
 * @file 改派详情
 * @author 刘翟
 * @date 2021-09-25 15:24:11
 */

layui.define(
    ['element', 'list_modify_operation', 'zmnUtils',
        'layer', 'table', 'clipboard', 'upload', 'form', 'zmnSelect',
        'zmnOmsSelect', '$http', 'previewer', 'select2', '$api'], function (exports) {

        let $ = layui.$;
        let form = layui.form;
        let $http = layui.$http;
        let layer = layui.layer;
        var zmnUtils = layui.zmnUtils;
        var zmnSelect = layui.zmnSelect;
        var operationUtils = layui.list_modify_operation;
        var table = layui.table;
        var element = layui.element;
        var clipboard = layui.clipboard;
        var previewer = layui.previewer;
        var select2 = layui.select2;
        var countyData = [];
        var showCheckCityMsg = false;

        // 城市数据
        var cityData = {};
        // 是否渲染过不可派单师傅
        var hasRender = 1;
        // 是否已经加载完毕工程师地图
        var isInitedEngineerMap = false;
        // 是否禁止提交
        var prohibitSubmit = false;
        // 最近一次选择的服务分类Id
        var recentlyServCategId = infoDataVO.servCategId;

        let iframeTypeNames = {
            1: '详情',
            2: '审核',
            3: '备注'
        }

        /**
         * 初始化派单请求参数
         */
        var initialDistributeParams = {};

        // 品类错误请求参数
        initialDistributeParams[categoryWrongReasonType] = {
            servCategId: infoDataVO.servCategId,
            categId: infoDataVO.categId,
            productId: infoDataVO.productId,
        };

        // 地址错误请求参数
        initialDistributeParams[addressWrongReasonType] = {
            longitude: infoDataVO.longitude,
            latitude: infoDataVO.latitude,
            countyId: infoDataVO.countyId,
            streetId: infoDataVO.streetId
        }

        var templeteFormatter = {
            masterInfoTempleteFunc: function (d) {
                return '<div><span class="master" id="' + d.masterId + '"></span></div>';
            },
            masterNameTempleteFunc: function (d) {
                var text = d.masterName + '—' + zmnUtils.maskPhone(d.masterPhone);
                var jia = d.companyId == 45111;
                if (jia) {
                    text += "—家";
                }
                var isReworkMaster = distributeInfoJson.reworkMasterId === d.masterId;
                var showVoice = d.nonDistributeFlag === undefined;

                return (`
               <div>
                   <div>
                        <span>${text}</span>
                        ${d.distributeRuleTitle ? `<span class="layui-badge layui-bg-green">${d.distributeRuleTitle}</span>` : ''}
                        ${d.novice ? `<span style="background-color: #669900 !important;" class="layui-badge">新手</span>` : ``}
                        ${d.channelExclusive ? `<span style="background-color: #FF6699 !important;" class="layui-badge">专属</span>` : ``}
                        ${isReworkMaster ? '<span class="layui-badge">源工程师</span>' : ''}
                        ${d.useStock ? `<span class="layui-badge layui-bg-green btn-stock" data-id="${d.masterId}">库存</span>` : ''}
                        ${canNetCall && showVoice ? `<a class="zmn-btn-text btn-netcall" data-id="${d.masterId}"><i class="zmn-icon zmn-icon-voice"></i></a>` : ''}
                    </div>
                </div>
            `);
            },
            MapMasterNameTempleteFunc: function (d) {
                var text = d.masterName + '—' + zmnUtils.maskPhone(d.masterPhone);
                var jia = d.companyId == 45111;
                if (jia) {
                    text += "—家";
                }
                var isReworkMaster = distributeInfoJson.reworkMasterId === d.masterId;
                var showVoice = d.nonDistributeFlag === undefined;

                return (`
               <div>
                   <div>
                        <span>${text}</span>
                        ${canNetCall && showVoice ? `<a class="zmn-btn-text btn-netcall" data-id="${d.masterId}"><i class="zmn-icon zmn-icon-voice"></i></a>` : ''}
                        <br>
                        ${d.distributeRuleTitle ? `<span class="layui-badge layui-bg-green">${d.distributeRuleTitle}</span>` : ''}
                        ${d.agent == 1 ? `<span class="layui-badge agent">直</span>` : `<span class="layui-badge no-agent">非</span>`}
                        ${d.novice ? `<span style="background-color: #669900 !important;" class="layui-badge">新手</span>` : ``}
                        ${d.channelExclusive ? `<span style="background-color: #FF6699 !important;" class="layui-badge">专属</span>` : ``}
                        ${d.workspaceType == 1 ? `<span class="layui-badge main-grid">主</span>` : `<span class="layui-badge no-main-gird">副</span>`}
                        ${isReworkMaster ? '<span class="layui-badge">源工程师</span>' : ''}
                    </div>
                </div>
            `);
            },
            NonMapMasterNameTempleteFunc: function (d) {
                var text = d.masterName + '—' + zmnUtils.maskPhone(d.masterPhone);
                var jia = d.companyId == 45111;
                if (jia) {
                    text += "—家";
                }
                if (d.distance) {
                    text += "—" + d.distance + "KM";
                }
                var isReworkMaster = distributeInfoJson.reworkMasterId === d.masterId;
                var showVoice = d.nonDistributeFlag === undefined;

                return (`
               <div>
                   <div>
                        <span>${text}</span>
                        ${canNetCall && showVoice ? `<a class="zmn-btn-text btn-netcall" data-id="${d.masterId}"><i class="zmn-icon zmn-icon-voice"></i></a>` : ''}
                        <br>
                        ${d.distributeRuleTitle ? `<span class="layui-badge layui-bg-green">${d.distributeRuleTitle}</span>` : ''}
                        ${d.agent == 1 ? `<span class="layui-badge agent">直</span>` : `<span class="layui-badge no-agent">非</span>`}
                        ${d.novice ? `<span style="background-color: #669900 !important;" class="layui-badge">新手</span>` : ``}
                        ${d.channelExclusive ? `<span style="background-color: #FF6699 !important;" class="layui-badge">专属</span>` : ``}
                        ${isReworkMaster ? '<span class="layui-badge">源工程师</span>' : ''}
                    </div>
                </div>
            `);
            }
        }
        // 派单信息Json
        var distributeInfoJson = {};
        // 所有工程师列表
        var allMasterList;
        var nonGirdMasterList;

        /**
         * 直营/非直营
         * @param agent
         * @returns {string}
         */
        function masterAgent(agent) {
            if (agent == 1) {
                return "直营";
            } else {
                return "非直营";
            }
        }

        /**
         * 主/副网格
         * @param gird
         */
        function masterWorkspaceType(workspaceType) {
            if (workspaceType == 1) {
                return "主";
            } else if (workspaceType == 2) {
                return "副";
            } else {
                return "-";
            }
        }

        /**
         * 处理单时比，保留3位小数
         * @param flag
         * @param value
         * @returns {string|*}
         */
        function processDatumOrderHourRatio(flag, value) {
            return changeDecimalBuZero(value, 3);
        }

        var verifyRules = {
            // 验证长度
            maxLengthFactory: function (length) {
                return function (value) {
                    if (value.length > length) {
                        return '输入字符超过最大长度，最大长度为：' + length;
                    } else {
                        return;
                    }
                };
            }
        }

        /**
         * 单时比小数位处理
         * @param number
         * @param bitNum
         * @returns {string|number}
         */
        function changeDecimalBuZero(number, bitNum) {
            /// 小数位不够，用0补足位数
            number = number / 1000;
            var f_x = parseFloat(number);
            if (isNaN(f_x)) {
                return '0.000';
            }
            var s_x = number.toString();
            var pos_decimal = s_x.indexOf('.');
            if (pos_decimal < 0) {
                pos_decimal = s_x.length;
                s_x += '.';
            }
            while (s_x.length <= pos_decimal + bitNum) {
                s_x += '0';
            }
            return s_x;
        }

        /**
         * 最优库存处理
         * @param value
         * @returns {string|string}
         */
        function processStockType(value) {
            if (value == 0) {
                return '<span class="layui-badge layui-bg-blue">满足</span>';
            } else if (value == 1 || value == 2) {
                return '<span class="layui-badge layui-bg-gray">不满足</span>';
            } else {
                return '-'
            }
        }

        /**
         * 网格内工程师列表
         * @type {function(): *}
         */
        var createTableCols = function () {
            var cols;
            var normalColsData = [
                {type: 'radio', hide: true},
                {field: 'distributeGrid', hide: true},
                {
                    field: 'masterName',
                    title: '工程师（双击可选中工程师）',
                    sort: true,
                    fixed: 'left',
                    minWidth: 290,
                    templet: templeteFormatter.masterNameTempleteFunc
                },
                {
                    field: 'agent', minWidth: 80, title: '合作类型', sort: true, align: 'center', templet: function (data) {
                        return masterAgent(data.agent)
                    }
                },
                {field: 'spName', minWidth: 110, title: '所属服务公司', sort: true, align: 'center'},
                {field: 'starLevel', minWidth: 60, title: '星级', sort: true, align: 'center'},
                {
                    field: 'workspaceType',
                    minWidth: 80,
                    title: '网格类型',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return masterWorkspaceType(data.workspaceType)
                    }
                },
                {field: 'recommendScore', minWidth: 110, title: '系统推荐分值', sort: true, align: 'center'},
                {
                    field: 'distance',
                    minWidth: 60,
                    title: '距离',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.distance ? data.distance + 'KM' : '';
                    }
                },
                {
                    field: 'datumOrderHourRatio',
                    minWidth: 70,
                    title: '单时比',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return processDatumOrderHourRatio(data.nonDistributeFlag, data.datumOrderHourRatio)
                    }
                },
                {
                    field: 'handCountRatio',
                    minWidth: 110,
                    title: '手头单占比',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.handCountRatio + '%';
                    }
                },
                {field: 'distributeNewCount', minWidth: 110, title: '新单派单量', sort: true, align: 'center'},
                {field: 'starLevelScore', minWidth: 70, title: '星级分', sort: true, align: 'center'},
                {field: 'compositeScore', minWidth: 70, title: '服务分', sort: true, align: 'center'},
                {
                    field: 'onlineStatus',
                    minWidth: 60,
                    title: '在线',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.onlineStatus == 2 ? '<span class="layui-badge layui-bg-blue">在线</span>' : '<span class="layui-badge layui-bg-gray">离线</span>';
                    }
                },
                {field: 'engineerStatusName', minWidth: 60, title: '状态', sort: true, align: 'center'},
                {
                    field: 'mainSkillId',
                    minWidth: 70,
                    title: '主技能',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.mainSkillId === distributeInfoJson.mainSkillId ? '<span class="layui-badge layui-bg-blue">满足</span>' : '<span class="layui-badge layui-bg-gray">不满足</span>';
                    }
                },
                {
                    stockCity: 'stockCity',
                    field: 'stockType',
                    minWidth: 80,
                    title: '最优库存',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return processStockType(data.stockType);
                    }
                },
                {field: 'handCount', minWidth: 70, title: '手头单', sort: true, align: 'center'},
                {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
            ].filter((item) => {
                return !item.stockCity || distributeInfoJson.stockCity;
            });

            cols = [normalColsData];
            return function () {
                return cols;
            }
        };

        /**
         * 网格外工程师列表
         * @type {function(): *}
         */
        var nonCreateTableCols = (function () {
            var cols;

            var normalColsData = [
                {type: 'radio', hide: true},
                {field: 'distributeGrid', hide: true},
                {
                    field: 'masterName',
                    title: '工程师（双击可选中工程师）',
                    sort: true,
                    fixed: 'left',
                    minWidth: 290,
                    templet: templeteFormatter.masterNameTempleteFunc
                },
                {
                    field: 'agent', minWidth: 80, title: '合作类型', sort: true, align: 'center', templet: function (data) {
                        return masterAgent(data.agent)
                    }
                },
                {field: 'spName', minWidth: 110, title: '所属服务公司', sort: true, align: 'center'},
                {field: 'starLevel', minWidth: 60, title: '星级', sort: true, align: 'center'},
                {field: 'recommendScore', minWidth: 110, title: '系统推荐分值', sort: true, align: 'center'},
                {
                    field: 'distance',
                    minWidth: 60,
                    title: '距离',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.distance ? data.distance + 'KM' : '';
                    }
                },
                {
                    field: 'datumOrderHourRatio',
                    minWidth: 70,
                    title: '单时比',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return processDatumOrderHourRatio(data.nonDistributeFlag, data.datumOrderHourRatio)
                    }
                },
                {
                    field: 'handCountRatio',
                    minWidth: 110,
                    title: '手头单占比',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.handCountRatio + '%';
                    }
                },
                {field: 'distributeNewCount', minWidth: 110, title: '新单派单量', sort: true, align: 'center'},
                {field: 'starLevelScore', minWidth: 70, title: '星级分', sort: true, align: 'center'},
                {field: 'compositeScore', minWidth: 70, title: '服务分', sort: true, align: 'center'},
                {
                    field: 'onlineStatus',
                    minWidth: 60,
                    title: '在线',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.onlineStatus == 2 ? '<span class="layui-badge layui-bg-blue">在线</span>' : '<span class="layui-badge layui-bg-gray">离线</span>';
                    }
                },
                {field: 'engineerStatusName', minWidth: 60, title: '状态', sort: true, align: 'center'},
                {
                    field: 'mainSkillId',
                    minWidth: 70,
                    title: '主技能',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return data.mainSkillId === distributeInfoJson.mainSkillId ? '<span class="layui-badge layui-bg-blue">满足</span>' : '<span class="layui-badge layui-bg-gray">不满足</span>';
                    }
                },
                {field: 'sortMainSkillId', minWidth: 70, hide: true, title: '主技能', sort: true, align: 'center'},
                {
                    stockCity: 'stockCity',
                    field: 'stockType',
                    minWidth: 110,
                    title: '最优库存',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return processStockType(data.stockType);
                    }
                },
                {field: 'handCount', minWidth: 70, title: '手头单', sort: true, align: 'center'},
                {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
            ].filter((item) => {
                return !item.stockCity || distributeInfoJson.stockCity;
            });

            cols = [normalColsData];

            return function () {
                return cols;
            }
        });

        var options = {
            saveURL: null,
            isNew: false,
            isEntrust: false,
            isDistributeMaster: false,
            modifyDetail: false,
            success: () => {
            },
        };


        /**
         * 获取敏感信息明文URL
         */
        let SHOW_HIDEINFO_URL = OMS_BASE_URL + '/work/redistribute/show/hideInfo.action';
        /**
         * 改派基础URL
         */
        let DISTRIBUTE_BASE_URL = OMS_BASE_URL + '/work/redistribute';
        /**
         * 申请改派URL
         */
        let APPLY_AUDIT_URL = DISTRIBUTE_BASE_URL + '/applyAudit.action';
        /**
         * 获取可改派工程师列表URL
         */
        let LIST_REDISTRIBUTE_ENGINEER_URL = OMS_BASE_URL + '/work/redistribute/listRedistributeEngineer.action'
        /**
         * 获取可改派工程师列表URL
         */
        let FETCH_DISTRIBUTE_INFO_URL = OMS_BASE_URL + '/work/redistribute/getDistributeInfo.action'
        /**
         * 新增备注 URL
         */
        let ADD_REMARK_URL = OMS_BASE_URL + '/work/redistribute/addRemark.action'
        /**
         * 通话记录
         */
        var OMS_ORDER_CALL_LOG_URL = OMS_BASE_URL + "/work/modify/callRecord.action";
        /**
         * 检查是否有在途重复的订单URL
         */
        let CHECK_SERVING_DUPLICATE_URL = OMS_BASE_URL + '/work/redistribute/checkServingDuplicateOrder.action'
        /**
         * 取得订单地址URL
         */
        let FETCH_ORDER_ADDRESS_URL = OMS_BASE_URL + '/work/redistribute/getOrderAddress.action'
        /**
         * 改派详情地址 URL
         */
        let DETAIL_PAGE_URL = OMS_BASE_URL + "/work/redistribute/detail.action";


        // 获取产品列表
        var PRODUCT_URL = "/serv/product/list.action";

        // 百度地图地址联想
        var BAIDU_MAP_SUGGESTED = "//api.map.baidu.com/place/v2/suggestion";

        // 校验地址是否在服务范围
        var STREET_VALIDATION_URL = "/area/checkServicePoint.action";

        // 根据经纬度获取区域信息
        var AREA_INFO_URL = "/area/getAreaInfo.action";

        // 检查是否可以下拉选择
        var CHECK_PRODECT = "/serv/check/repeat/product.action";

        // 工程师远程查询 URL
        var MASTER_LIST_URL = '/staff/master/list.action';

        // 校验工程师派单
        var MASTER_CHECK_URL = '/work/redistribute/checkEngineer.action';

        // 获取省份、城市、区域
        var CITY_URL = "/area/permit/city/list.action";
        var COUNTY_URL = "/area/list.action";
        var AREA_DETAIL_URL = "/area/detail/list.action";

        let detailConfig = {
            // 是否可以获取工程师列表，条件： 审核类型：【员工审核】 且 改派类型：【指定改派】
            hasCanFetchRedistributeEngineer: infoDataVO.auditType == 2 && infoDataVO.redistributeType == 2
        }

        table.init('zmn-table-spurious-standard', {
            limit: 6,
            page: false
        });

        var getters = {
            getInputValueById: function (id) {
                return $.trim($("#" + id).val());
            },
            getLocation: function () {
                return {
                    lng: $("#longitude").val(),
                    lat: $("#latitude").val(),
                };
            },
            getLongitude: function () {
                return $("#longitude").val();
            },
            getLatitude: function () {
                return $("#latitude").val();
            },
            getPlatWork: function () {
                return $("#platWork").val() || $("#plat").val() || platMark.ZMN;
            },
            getProvinceId: function () {
                return getLayuiSelectValue("#provinceId");
            },
            getProvinceName: function () {
                return getLayuiSelectText("#provinceId");
            },
            getCityId: function () {
                return getLayuiSelectValue("#cityId");
            },
            getCityName: function () {
                return getLayuiSelectText("#cityId");
            },
            getCountyId: function () {
                return this.getInputValueById("countyId");
            },
            getInputCountyName: function () {
                let countyId = this.getCountyId();
                if (!countyId) return "";
                return $('#county-list').find('span[data-id=' + countyId + ']').text();
            },
            getStreetId: function () {
                return this.getInputValueById("streetId");
            },
            getCityName: function () {
                return $("#cityId option:selected").text();
            },
            getStreet: function () {
                return $("#customerAddress").val();
            },
            getStreetSource: function () {
                return $('#streetSource').val() || 0;
            },
            getAddress: function () {
                return $('input[name="address"]').val();
            }
        };


        /**
         * 获取派单信息（包含可派单的工程师列表）
         *
         * @param params
         */
        function fetchDistributeInfo(params) {
            let requestParams = Object.assign({orderId: infoDataVO.orderId, workId: infoDataVO.workId}, params)
            return $http.get(FETCH_DISTRIBUTE_INFO_URL, requestParams);
        }

        /**
         * 添加备注
         */
        function addLastRemark(params) {
            return $http.$post(ADD_REMARK_URL,
                {
                    orderId: infoDataVO.orderId,
                    workId: infoDataVO.workId,
                    redistributeId: infoDataVO.redistributeId,
                    lastRemark: params.lastRemark,
                });
        }

        /**
         * 校验是否有其他的在途重复订单
         */
        function checkServingDuplicateOrder(data) {
            $http.$get(CHECK_SERVING_DUPLICATE_URL, {
                orderId: infoDataVO.orderId,
                workId: infoDataVO.workId,
                servCategId: data.servCategId || null,
                categId: data.categId || null,
                productId: data.productId || null,
                longitude: data.longitude || null,
                latitude: data.latitude || null,
            }).then(result => {
                // 是否有在途重复的单子，有就给出提示。
                if (result) {
                    $("#servingDuplicateNotice").show()
                } else {
                    $("#servingDuplicateNotice").hide()
                }
            }, err => {
                console.log(err)
            })
            return;
        }

        /**
         * 检查工程师是否可派单
         */
        function checkMasterDistributable(params) {
            var def = $.Deferred();
            var masterId = +params.masterId;

            $http.get(MASTER_CHECK_URL, params).then(function (data) {
                if (data.status === 2) {
                    def.resolve(masterId, data.reason);
                } else {
                    def.reject(data.reason);
                }
            }, function (msg) {
                layer.msg(msg);
                def.reject('校验失败');
            });

            return def.promise();
        }

        function getLayuiSelectValue(selector) {
            return $(selector + " option:selected").val();
        }

        function getLayuiSelectText(selector) {
            return $(selector + " option:selected").text();
        }

        /**
         * 根据父级 id 远程获取下级区域数据
         * @param {string} url 地址
         * @param {object} params 参数
         */
        function fetchAreaDataByParentId(url, params) {
            return $http.get(url, params).then(
                function (data) {
                    return data;
                },
                function () {
                    layer.msg("获取数据失败");
                    return $.Deferred().resolve([]);
                }
            );
        }

        /**
         * 根据省份 id 远程获取城市数据
         * @param provinceId 城市 id
         */
        function fetchCityData(provinceId) {
            return fetchAreaDataByParentId(CITY_URL, {
                provinceId: provinceId
            });
        }

        /**
         * 获取后台产品分类
         * @param params 查询参数
         * @returns {*}
         * @private
         */
        function fetchProductByServcate(params) {
            return $http.$get(PRODUCT_URL, params);
        }

        /**
         * 根据城市 id 远程获取区域数据
         * @param cityId 城市 id
         */
        function fetchAreaData(cityId) {
            return fetchAreaDataByParentId(COUNTY_URL, {parentId: cityId});
        }

        /**
         * 根据城市 id 远程获取区域数据
         * @param cityId 城市 id
         */
        function fetchAreaDetailData(pId) {
            return fetchAreaDataByParentId(AREA_DETAIL_URL, {parentId: pId});
        }

        /**
         * 根据经纬度 远程获取区域数据
         * @param cityId 城市 id
         */
        function fetchAreaInfo(lon, lat) {
            return fetchAreaDataByParentId(AREA_INFO_URL, {
                longitude: lon,
                latitude: lat,
            });
        }

        /**
         * 获取区县信息查询
         */
        function getCountyInfo(countyName) {
            if (!countyName) {
                return null;
            }

            if (countyData.length == 0) {
                $('#county-list').find('span').each(function () {
                    var county = {
                        countyId: $(this).data('id'),
                        countyName: $(this).text(),
                    };
                    countyData.push(county);
                });
            }

            for (var i = 0; i < countyData.length; i++) {
                if (countyName == countyData[i].countyName) {
                    return countyData[i];
                }
            }
            return null;
        }

        /**
         * 渲染后台产品下拉框
         * @param {object} data
         * @param callback
         * @private
         */
        function _renderProductSelect(data, callback = null) {

            let htmlStr = '<option value="">全部</option>';
            data.forEach(function (item) {
                // ext2是二级分类Id
                htmlStr += '<option data-serv-categ-id="' + item.pid + '" data-categ-id="' + item.ext2 + '" value="' + item.value + '">' + item.text + '</option>';
            });

            // 渲染产品下拉框
            $('#productId').html(htmlStr);

            if (typeof callback === "function") {
                callback();
            }

            form.render("select");
        }

        function renderProductSelect(servCategId, callback = null) {
            fetchProductByServcate({
                servCategId: servCategId,
                showType: 1
            }).then((data) => {
                /* 渲染产品下拉框 */
                _renderProductSelect(data, callback)
            }, () => {
                /* 清空产品下拉框 */
                _renderProductSelect([]);
            });
        }

        /**
         * 区县信息查询
         */
        function setCountyInfo(countyName, lng, lat, callback) {
            var cityId = $('#cityId option:selected').val();
            // 本地数据获取countyinfo
            countyName = countyName || '';
            let countyInfo = getCountyInfo(countyName);
            if (countyInfo) {
                updateAreaInfo(countyInfo.countyId);
                if (callback) {
                    callback(countyInfo.countyId);
                }
                return;
            }

            // 调用远程接口获取countyinfo
            fetchAreaInfo(lng, lat).then(function (data) {
                if (cityId != data.cityId) {
                    switchCity(data.cityId);
                }

                updateAreaInfo(data.countyId);
                if (callback) {
                    callback(data.countyId);
                }
            }, function (msg) {
                layer.msg(msg);
            });
        }

        /**
         * 获取百度联想出的地址
         * @param params 查询参数
         * @param cb 回调函数
         */
        function fetchSuggestedStreet(params, cb) {
            fetchBaiduSuggestedStreet(params, cb);
        }


        /**
         * 点击地图旁的工程师列表，更改选中的工程师
         * @param masterId
         * @param masterInfo
         * @param nonMap
         */
        function updateMasterSelect(data, isInitMasterSelect) {
            if (isInitMasterSelect) {
                updateNonMasterSelect(data);
            } else {
                form.val('zmn-form', {masterId: data.masterId});
                $('#masterSelect').val(data.masterId);
            }
        }


        /**
         * 工程师下拉框是否存在当前工程师，若不存在，则塞到工程师的下拉框中
         * @param data
         */
        function updateNonMasterSelect(data) {

            // 如果工程师下拉框缺少当前工程师，则渲染到工程师下拉框中
            renderMasterSelect(data);

            form.val('zmn-form', {masterId: data.masterId});
            $('#masterSelect').val(data.masterId);
        }

        /**
         * 渲染工程师下拉框
         * @param data 工程师数据
         */
        function renderMasterSelect(data) {
            let masterId = data.masterId;
            let masterInfo = data.masterName + '—' + zmnUtils.maskPhone(data.masterPhone);

            // 工程师下拉框是否存在当前工程师
            let isExist = false;
            $("#masterSelect option").each(function () {
                if ($(this).val() == masterId) {
                    isExist = true;
                    return false;
                }
            });

            // 若不存在，则塞到工程师的下拉框中
            if (!isExist) {
                $("#masterSelect").append(`<option value='${masterId}'
                                                    class='master-options'
                                                    data-master-name='${data.masterName}'
                                                    data-distribute-grid='${data.distributeGrid}'>${masterInfo}</option>`);
                form.render('select');
            }
        }


        /**
         * 获取百度联想出的地址
         * @param params 查询参数
         * @param cb 回调函数
         */
        function fetchBaiduSuggestedStreet(params, cb) {
            $.ajax({
                url: BAIDU_MAP_SUGGESTED,
                type: "GET",
                dataType: "jsonp",
                data: {
                    query: params.queryStr,
                    region: params.cityName,
                    city_limit: true,
                    output: "json",
                    ak: params.ak,
                },
                success: function (response) {
                    if (response.status === 0) {
                        // 过滤搜索结果
                        var data = response.result.filter((item) => {
                            if (item.name == item.province || item.name == item.city || item.name == item.district || item.name.endsWith('-道路') || item.name.endsWith('镇') || item.name.endsWith('乡')) {
                                return false;
                            }
                            return (item.city.indexOf(params.cityName.slice(0, 1)) !== -1) || (!item.city && item.district.indexOf(params.cityName.slice(0, 1)) !== -1);
                        });
                        cb(data);
                    }
                },
            });
        }

        //检查下拉是否可以选择
        function checkProdect(params, cb1, cb2) {
            $.ajax({
                type: "post",
                url: CHECK_PRODECT,
                data: JSON.stringify(params),
                contentType: "application/json;charset=UTF-8",
                success: function (res) {
                    res;
                    if (res.statusBool == true) {
                        cb1();
                    } else {
                        layer.alert(res.message);
                        cb2();
                    }
                },
                error: function () {
                },
            });
        }

        /**
         * 格式化工程师列表列表项
         * @param {object} repo
         * @returns {string}
         */
        function formatRepoForMaster(repo) {
            if (repo.loading) {
                return '查询中...'
            }
            var name = repo.text + (repo.disabled ? '（离职）' : '');
            var markup = '<div><div><i class="zmn-icon zmn-icon-worker"></i><span>' + name + '</span></div><div><i class="zmn-icon zmn-icon-phone"></i><span>' + repo.ext1 + '</span></div></div>';

            return markup;
        }

        /**
         * 呼叫中心打电话
         * @param telephone
         */
        function makeCallCenterCall(telephone) {
            top.postMessage({
                type: 2,
                phone: telephone,
                bizId: infoDataVO.redistributeId,
                outBusinessType: 11,
                channelId: infoDataVO.channelId,
            }, '*');
        }

        /**
         * 城市选择下拉框选中事件处理函数
         */
        function handleCountySelect(countyId, cb) {
            if (countyId) {
                fetchAreaDetailData(countyId).done(function (data) {
                    renderStreetIdSelect(data, cb);
                });
            }
        }

        function verifyStreetValidation(params) {
            params.type = getters.getOrderType();
            params.add = options.isNew ? 2 : 1;
            return $http.get(STREET_VALIDATION_URL, params).then(function (data) {
                if (data.status !== 2) {
                    return $.Deferred().reject("所选地址不在服务范围");
                }
                var $city = $('#cityId option[value="' + data.cityId + '"]:selected');

                if (!$city[0]) {
                    return $.Deferred().reject("所选地址与所选城市不匹配");
                }

                return data;
            });
        }

        /**
         *  标准需要查询的城市名称
         * @param cityName 城市名称
         * @returns {String}
         */
        function normalizeCityName(cityName) {
            return cityName.replace("辖县", "").replace("辖区", "");
        }

        /**
         * 获取城市名称
         * @returns {String} 城市名称
         */
        function getSelectedCityName() {
            return normalizeCityName($("#cityId option:selected").text());
        }

        /**
         * 分点城市切换主城市
         * @returns {String} 城市名称
         */

        function switchCity(cityId) {
            var $cityId = $("#cityId");
            $cityId.val(cityId);
            form.render("select");

            updateOptionsStatus($cityId);
        }

        /**
         * 更新 区域列表
         * @param countyId 区域 Id
         */
        function updateAreaList(countyId) {
            var $areaItems = $("#county-list span");
            $areaItems.removeClass("current");
            if (!countyId) {
                return;
            }

            $areaItems.filter('[data-id="' + countyId + '"]').addClass("current");
        }

        /**
         * 更新区域输入框的值
         * @param countyId 区域 Id
         */
        function updateAreaInput(countyId) {
            $("#countyId").val(countyId);
        }

        /**
         * 更新区域相关信息
         * @param countyId 区域 Id
         */
        function updateAreaInfo(countyId) {
            updateAreaList(countyId);
            updateAreaInput(countyId);
        }

        /**
         * 更新服务坐标信息
         * @param lnt 经度
         * @param lat 纬度
         */
        function setStreetSource(value) {
            $('#streetSource').val(value);
        }

        function setStreetId(value) {
            $('#communityId').val(value);
        }

        function updateLocationInfo(lnt, lat) {
            $("#longitude").val(lnt);
            $("#latitude").val(lat);
        }

        /**
         * 更新街道信息
         * @param {string} value 街道信息
         */
        function updateStreetInfo(value) {
            $("#customerAddress").val(value);
        }

        /**
         * 更新街道信息
         * @param {string} value 街道信息
         */
        function updateDistrict(value) {
            $("#district").val(value);
        }

        /**
         * 清空地址相关数据
         */
        function clearAddress() {
            var inputArray = ["#customerAddress", "#longitude", "#latitude", "#communityId", "#streetSource"];

            $.each(inputArray, function (index, selector) {
                clearInputValue(selector);
            });

            var selectArray = ["#countyId", "#streetId"];

            $.each(selectArray, function (index, selector) {
                clearSelectValue(selector);
            });

            form.render("select");

            setTimeout(function () {
                $("#suggestPanel ul").html("");
                $("#suggestPanel").hide();
            }, 300);
        }

        /**
         * 重新生成模糊地址数据
         */
        function recreatFuzzyInfo() {
            var $street = $("#streetId option:selected");
            if ($street) {
                var lon = $street.data("longitude");
                var lat = $street.data("latitude");
                var id = $street.val();
                if (!id == "") {
                    if (!lon || !lat) {
                        $street.prop("selected", false);
                        layer.msg("所选街道无经纬度数据，请到基础数据中心完善配置");
                        return;
                    }
                    $("#longitude").val(lon);
                    $("#latitude").val(lat);
                    $("#customerAddress").val($street.text());
                    $('#streetSource').val(3);

                    // 渲染派单地图
                    renderDistributeMap({
                        longitude: lon,
                        latitude: lat,
                        countyId: getters.getCountyId(),
                        streetId: $street.val()
                    })
                }
            }
        }

        /**
         * 清空输入框的值
         */
        function clearInputValue(selector) {
            $(selector).val("");
        }

        /**
         * 清空输入框的值
         */
        function clearSelectValue(selector) {
            var selectedOption = selector + " option:selected";
            $(selectedOption).prop("selected", false);
        }

        /**
         * 显示模糊地址选择框
         */
        function initFuzzyAddress() {
            var $this = $("#address-type-exact");
            $this.addClass("layui-hide");
            $("#exact-address").addClass("layui-hide");
            $("#address-type-fuzzy").removeClass("layui-hide");
            $("#fuzzy-address").removeClass("layui-hide");
            clearAddress();

            $("#customerAddress").attr("lay-verify", "");
            $("#countyId").attr("lay-verify", "required");
            $("#streetId").attr("lay-verify", "required");
        }

        /**
         * 显示精确地址选择框
         */
        function initExactAddress() {
            var $this = $("#address-type-fuzzy");
            $this.addClass("layui-hide");
            $("#fuzzy-address").addClass("layui-hide");
            $("#address-type-exact").removeClass("layui-hide");
            $("#exact-address").removeClass("layui-hide");
            clearAddress();

            $("#customerAddress").attr("lay-verify", "required");
            $("#countyId").attr("lay-verify", "");
            $("#streetId").attr("lay-verify", "");
        }


        /**
         * 检查百度地图插件是否可用
         * @returns {{msg: string, status: boolean}}
         */
        function checkMapAvailability() {
            var result = {
                status: true,
                msg: "",
            };

            var cityId = $("#cityId option:selected").val();

            if (!cityId) {
                result = {
                    status: false,
                    msg: "请先选择城市",
                };
            }

            return result;
        }

        function showOrderAddress($target) {
            $http.get(FETCH_ORDER_ADDRESS_URL, {
                orderId: infoDataVO.orderId,
            }).then(function (data) {
                $target.text(data);
            }, function (msg) {
                layer.msg(msg);
            });
        }


        function showOrCallPhone($targetId, type, phoneIndex, addressType) {
            $http.get(SHOW_HIDEINFO_URL, {
                redistributeId: infoDataVO.redistributeId,
                type: type,
                phoneIndex: phoneIndex,
                addressType: addressType
            }).then(function (data) {
                // 如果不是要解密 就是要打电话
                if (zmnUtil.isNull($targetId)) {
                    console.log("向用户拨打电话")
                    makeCallCenterCall(data);
                    return;
                }
                $targetId.text(data);
            }, function (msg) {
                layer.msg(msg);
            });
        }

        /**
         * 更新下拉框选项的状态。1. 当前元素不可点击 2. 其余可以选项可以点击
         * @param elem select dom 元素
         */
        function updateOptionsStatus(elem, index) {
            $(elem)
                .find("option")
                .attr("disabled", false)
                .filter(":selected")
                .attr("disabled", true);
            if (index >= 0) {
                form.render("select", "servCategoryA" + index);
            } else {
                form.render("select", "adress");
            }
        }

        function renderDetailMasterList(data) {
            table.render({
                elem: '#detailMasterTable',
                height: 400,
                limit: 1000,
                data: data || [],
                skin: 'line',
                cols: createTableCols()(),
                done: function (res, curr, count) {
                    var re = res.data;
                    if (re.length > 0) {
                        for (var i in res.data) {
                            var item = res.data[i];
                            if (item.nonDistributeFlag != undefined) {
                                $('tr[data-index=' + i + ']').prop('disabled', true);
                                $("tr[data-index='" + i + "']").attr({"style": "background:#F2F2F2;color:#999999"});  //将当前行变成绿色
                            }
                        }
                    }
                }
            });

            data.forEach(data => {
                renderMasterSelect(data)
            })

        }

        /**
         * 渲染不可派单列表
         * @param data
         */
        function renderNonDetailMasterList(data) {
            if (data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].mainSkillId === distributeInfoJson.mainSkillId) {
                        data[i].sortMainSkillId = 2;
                    } else {
                        data[i].sortMainSkillId = 1;
                    }
                }
            }
            table.render({
                elem: '#nonDetailMasterTable',
                height: 400,
                limit: 1000,
                data: data || [],
                skin: 'line',
                cols: nonCreateTableCols()(),
                initSort: {
                    field: 'sortMainSkillId',
                    type: 'desc'
                },
                done: function (res, curr, count) {
                    var re = res.data;
                    if (re.length > 0) {
                        for (var i in res.data) {
                            var item = res.data[i];
                            if (item.nonDistributeFlag != undefined) {
                                $('tr[data-index=' + i + ']').prop('disabled', true);
                                $("tr[data-index='" + i + "']").attr({"style": "background:#F2F2F2;color:#999999"});  //将当前行变成绿色
                            }
                        }
                    }
                }
            });

            // 排除不可派单工程师之后，渲染工程师下拉框
            data.filter(item => !item.nonDistributeFlag).forEach(item => {
                renderMasterSelect(item)
            })

        }

        /**
         * 渲染不可派单地图
         * @param data
         */
        function renderNonMasterPointsOfMap(data) {
            var map = new BMap.Map('nonMapOfmaterList');
            var point = new BMap.Point(distributeInfoJson.longitude, distributeInfoJson.latitude);
            map.centerAndZoom(point, 12);
            map.enableScrollWheelZoom(true);
            map.addControl(new BMap.NavigationControl({
                anchor: BMAP_ANCHOR_TOP_RIGHT,
                type: BMAP_NAVIGATION_CONTROL_ZOOM
            }));
            map.addControl(new BMap.OverviewMapControl());

            addMakerForCustomer(map, point);
            addMakerListForMaster(map, data, '#nonMapView, #nonTableView', nonGirdMasterList, true);
            addGridList(map, distributeInfoJson.gridList);
        }

        /**
         * 更新语音按钮状态
         * @param {boolean} disabled 是否禁用
         */
        function updateVoiceStatus(disabled) {
            var $voiceBtn = $('.zmn-btn-voice');
            $voiceBtn.prop('disabled', disabled);

            if (disabled) {
                $voiceBtn.addClass('layui-btn-disabled');
            } else {
                $voiceBtn.removeClass('layui-btn-disabled');
            }
        }

        function addMakerForCustomer(map, point) {
            var marker = new BMap.Marker(point, {
                icon: new BMap.Icon('/static/images/icon-repair.png', new BMap.Size(32, 32), {
                    // offset: new BMap.Size(10, 25), // 指定定位位置
                    imageSize: new BMap.Size(32, 32)
                })
            });
            map.addOverlay(marker);

            var label = new BMap.Label(distributeInfoJson.dutyInfo, {
                offset: new BMap.Size(0, -20)
            });
            label.setStyle({
                border: 'none',
                color: '#fff',
                backgroundColor: '#01AAED'
            });

            marker.setLabel(label);

            setInterval(function () {
                var rotation = marker.getRotation();
                marker.setRotation(rotation + 30);
            }, 100);
        }

        function addMakerListForMaster(map, data, view, masterList, nonMap) {
            if (!data) {
                return
            }
            makerList = [];
            var nearestMaster = data.reduce((acc, curr) => {
                if (curr.distance <= acc.distance) {
                    return curr;
                }

                return acc;
            }, {});

            data.forEach((master) => {
                var point = new BMap.Point(master.masterLng, master.masterLat);
                var marker = new BMap.Marker(point, {
                    icon: new BMap.Icon('/static/images/icon-master.png', new BMap.Size(70, 70), {
                        // offset: new BMap.Size(10, 25), // 指定定位位置
                        imageSize: new BMap.Size(70, 70)
                    })
                });

                var label = new BMap.Label('111');
                label.setStyle({
                    border: 0,
                    backgroundColor: '#1296DB',
                    fontSize: '16px',
                    color: '#fff',
                    borderRadius: '5px',
                    padding: '0 10px',
                    fontWeight: 900
                });
                label.setContent(master.distributeRuleTitle);
                label.setOffset(new BMap.Size(0, -20));
                marker.setLabel(label);

                marker.addEventListener('click', function () {
                    updateMasterSelect(master, nonMap);
                    updateMasterListTable(master.masterId, view, masterList);
                    updateVoiceStatus(false);
                });

                if (nearestMaster.masterId === master.masterId) {
                    var label = new BMap.Label('距离最近：' + master.distance, {
                        offset: new BMap.Size(0, -20)
                    });

                    label.setStyle({
                        border: 'none',
                        color: '#fff',
                        backgroundColor: '#01AAED'
                    });

                    marker.setLabel(label);
                }

                map.addOverlay(marker);

                makerList.push(marker);

                if (master.masterId === distributeInfoJson.masterId) {
                    marker.setAnimation(BMAP_ANIMATION_BOUNCE);
                }
            })
        }

        /**
         * 网格
         * @param map
         * @param data
         */
        function addGridList(map, data) {
            data.forEach((grid) => {
                let gridBaidu = grid.gridBaidu.replace("POLYGON((", "").replace("))", "");

                let maps = gridBaidu.split(",");
                let bmap3 = [];
                for (var j = 0; j < maps.length; j++) {
                    let point = maps[j].trim().split(/\s+/);
                    let bpoint = new BMap.Point(point[0], point[1]);
                    bmap3.push(bpoint);
                }

                let polygon = new BMap.Polygon(bmap3, {
                    strokeColor: 'blue',
                    strokeWeight: 2,
                    strokeOpacity: 0.5
                });
                map.addOverlay(polygon);

                // 获得中心点
                let centerPoint = getCenterPoint(polygon.getPath());
                let label = new BMap.Label(grid.gridName, {offset: new BMap.Size(-40, -25), position: centerPoint});
                label.setStyle({color: "#FF0000", fontSize: "12px", backgroundColor: "0.05", border: "0"});//对label 样式隐藏
                map.addOverlay(label);
            });
        }

        /**
         * 获得图形的中心点
         */
        function getCenterPoint(path) {
            var x = 0.0;
            var y = 0.0;
            for (var i = 0; i < path.length; i++) {
                x = x + parseFloat(path[i].lng);
                y = y + parseFloat(path[i].lat);
            }
            x = x / path.length;
            y = y / path.length;
            return new BMap.Point(x, y);
        }

        /**
         * 渲染不可派单列表
         * @param data
         */
        function renderNonSimpleMasterList(data) {
            table.render({
                elem: '#nonSimpleMasterTable',
                height: 400,
                limit: 1000,
                data: data || [],
                skin: 'line',
                cols: [[
                    {type: 'radio', hide: true},
                    {
                        field: 'masterName',
                        title: '工程师（双击可选中工程师）',
                        unresize: true,
                        templet: templeteFormatter.NonMapMasterNameTempleteFunc
                    },
                    {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
                ]],
                done: function (res, curr, count) {
                    // 如果【可以选择工程师】 并且 已经"选中"了【同意改派】，就显示出地图。
                    if (detailConfig.hasCanFetchRedistributeEngineer && $("input[name=auditStatus]").val() == 3) {
                        $("#choseRedistributeMaster").removeClass("layui-hide");
                        $("#distribute-item").removeClass("layui-hide");
                    }
                    isInitedEngineerMap = true;
                }
            });

        }

        function renderSimpleMasterList(data) {
            table.render({
                elem: '#simpleMasterTable',
                height: 400,
                limit: 1000,
                data: data || [],
                skin: 'line',
                cols: [[
                    {type: 'radio', hide: true},
                    {
                        field: 'masterName',
                        title: '工程师（双击可选中工程师）',
                        width: 296,
                        unresize: true,
                        templet: templeteFormatter.MapMasterNameTempleteFunc
                    },
                    {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
                ]],
                done: function (res, curr, count) {
                    // 如果【可以选择工程师】 并且 已经"选中"了【同意改派】，就显示出地图。
                    if (detailConfig.hasCanFetchRedistributeEngineer && $("input[name=auditStatus]:checked").val() == 3) {
                        $("#choseRedistributeMaster").removeClass("layui-hide");
                        $("#distribute-item").removeClass("layui-hide");
                    }
                    isInitedEngineerMap = true;
                }
            });
        }

        function renderMasterPointsOfMap(data) {
            var map = new BMap.Map('mapOfmaterList');
            var point = new BMap.Point(distributeInfoJson.longitude, distributeInfoJson.latitude);
            map.centerAndZoom(point, 12);
            map.enableScrollWheelZoom(true);
            map.addControl(new BMap.NavigationControl({
                anchor: BMAP_ANCHOR_TOP_RIGHT,
                type: BMAP_NAVIGATION_CONTROL_ZOOM
            }));
            map.addControl(new BMap.OverviewMapControl());

            addMakerForCustomer(map, point);
            addMakerListForMaster(map, data, '#mapView, #tableView', allMasterList, false);
            addGridList(map, distributeInfoJson.gridList);
        }

        function initMapViewOfMasterList(tabName, data) {
            if (tabName == 'nonDistributeList') {
                try {
                    renderNonMasterPointsOfMap(data);
                } catch (e) {
                    console.log(e);
                }
                renderNonSimpleMasterList(data);
            } else {
                try {
                    renderMasterPointsOfMap(data);
                } catch (e) {
                    console.log(e);
                }
                renderSimpleMasterList(data);
            }

        }

        function initTableViewOfMasterList(tabName, data) {

            // 重新渲染工程师下拉框
            $("#masterSelect").empty();
            $("#masterSelect").html(`<option value="">请选择</option>`);
            form.render('select');

            if (tabName == 'nonDistributeList') {
                renderNonDetailMasterList(data);
            } else {
                renderDetailMasterList(data);
            }
        }

        function updateMasterListTable(masterId, view, masterList) {
            var tableWrapperList = $(view);

            tableWrapperList.find('input[type="radio"]').prop('checked', false);
            tableWrapperList.find('.layui-table-main tr.current').removeClass('current');
            tableWrapperList.find('span.master[id="' + masterId + '"]')
                .closest('tr')
                .addClass('current')
                .find('input[type="radio"]')
                .prop('checked', true);
            form.render('radio');

            masterList.forEach((master) => {
                if (master.masterId === +masterId) {
                    master['LAY_CHECKED'] = true;
                } else {
                    master['LAY_CHECKED'] = false;
                }
            });
        }

        /**
         * 渲染城市选择下拉框
         * @param {array} data 城市数据
         */
        function renderCitySelect(data) {
            var htmlStr = '<option value=""></option>';

            var oldCityId = getters.getCityId();
            var oldCityName = getLayuiSelectText("#cityId");

            $.each(data, function (index, item) {
                htmlStr +=
                    '<option value="' +
                    item.value +
                    '" data-pid="' +
                    item.pid +
                    '" ' +
                    (oldCityId == item.value ? "selected " : " ") +
                    ">" +
                    item.text +
                    "</option>";
            });
            $("#cityId").html(htmlStr);
            form.render("select");

            var result = $.grep(data, function (e) {
                return e.value == oldCityId;
            });
            if (
                showCheckCityMsg &&
                options.isNew &&
                oldCityName != "" &&
                oldCityName != "市" &&
                result.length == 0
            ) {
                // 若未开通，清空：地址
                clearAddress();
                zmnUtils.layui.toastError(
                    "当前渠道未开通：" + oldCityName + "，请重新选择城市"
                );
            }
        }

        /**
         * 省份选择下拉框选中事件处理函数
         * @param provinceId 省份 id
         */
        function handleProvinceSelect(provinceId) {
            // 更新下拉框选项状态
            updateOptionsStatus($("#provinceId"));

            // 渲染城市下拉框
            initCitySelect(provinceId, infoDataVO.channelId, false);

            // 清空区域列表
            renderServiceArea([]);

            // 清空街道信息
            renderStreetIdSelect([]);

            // 清空地址
            clearAddress();
        }

        /**
         * 城市选择下拉框选中事件处理函数
         */
        function handleCitySelect(cityId) {
            var $city = $("#cityId");

            // 更新下拉框选项状态
            updateOptionsStatus($city);

            // 初始化服务区域
            initServiceArea(cityId);

            // 清空地址
            clearAddress();

            // 清空街道信息
            renderStreetIdSelect([]);
        }

        /**
         * 获取到 派单信息 之后的回调
         * @param result
         */
        function distributeInfoCallBack(result) {
            distributeInfoJson = result;

            // 初始化工程师列表数据
            allMasterList = distributeInfoJson.recommendMasterList || [];
            nonGirdMasterList = distributeInfoJson.nonGridDistributeMasterList || [];

            $("#girdId").val(result.gridId)
            $("#distributeWay").val(result.distributeWay)
        }

        /**
         * 渲染城市选择下拉框
         * @param provinceId 省份ID
         */
        function initCitySelect(provinceId, channelId, showMsg, cb) {
            showCheckCityMsg = showMsg;

            var key = provinceId;
            if (options.isNew) {
                key = (provinceId || 0) + "-" + channelId;
            } else {
                // provinceId 为空时执行
                if (!provinceId) {
                    renderCitySelect(distributeInfoJson.cityList);
                    if (cb) {
                        cb();
                    }
                    return;
                }
            }

            if (cityData[key]) {
                renderCitySelect(cityData[key]);
                if (cb) {
                    cb();
                }
            } else {
                fetchCityData(provinceId).done(function (data) {
                    cityData[key] = data;
                    renderCitySelect(data);
                    if (cb) {
                        cb();
                    }
                });
            }
        }

        /**
         * 初始化服务区域显示
         * 初始化区县下拉框
         * @param {array} data 服务区域列表
         */
        function renderServiceArea(data, cb) {
            var htmlStr = "";

            countyData = [];
            $.each(data, function (index, county) {
                if (!county.disabled) {
                    htmlStr += `<span class="county" data-id="${county.value}">${county.text}</span>`;
                    countyData.push({
                        countyId: county.value,
                        countyName: county.text
                    })
                }
            });

            var $serviceArea = $("#county-list");
            $serviceArea.html(htmlStr);

            var $countyId = $("#countyId");
            var optionHtmlStr = '<option value="">请选择区县</option>';

            var countyId = $countyId.val();
            $.each(data, function (index, county) {
                if (!county.disabled) {
                    if (countyId && county.value == countyId) {
                        optionHtmlStr += `<option value="${county.value}" selected="selected">${county.text}</option>`;
                    } else {
                        optionHtmlStr += `<option value="${county.value}">${county.text}</option>`;
                    }
                }
            });

            $countyId.html(optionHtmlStr);
            form.render("select");

            if (data.length) {
                $serviceArea.show();
            } else {
                $serviceArea.hide();
            }

            if (typeof cb === "function") {
                cb();
            }

            updateAreaList(getters.getCountyId());
        }

        /**
         * 初始化街道显示
         */
        function renderStreetIdSelect(data, cb) {
            var optionHtmlStr = '<option value="">请选择乡镇或街道</option>';

            $.each(data, function (index, street) {
                optionHtmlStr += `<option value="${street.areaId}" data-longitude="${street.longitude}" data-latitude="${street.latitude}">${street.name}</option>`;
            });

            $("#streetId").html(optionHtmlStr);
            form.render("select");

            if (typeof cb === "function") {
                cb();
            }
        }

        /**
         * 渲染派单地图
         * @param params
         */
        function renderDistributeMap(params) {

            if (detailConfig.hasCanFetchRedistributeEngineer) {
                fetchDistributeInfo(params).then(function (result) {

                    // 如果是同意改派，才展示出地图，否则就只是更新【可选工程师】的数据而已。
                    if ($("input[name='auditStatus']:checked").val() == 3) {
                        $("#distribute-item").removeClass("layui-hide");
                    }

                    // 回调函数目的是将响应赋值给全局变量
                    distributeInfoCallBack(result);

                    // 初始化校验工程师下拉框
                    initMasterSelecteBySelect2(result);

                    var resultList = result.nonDistributeMasterList

                    /* 渲染工程师列表 */
                    if (resultList != null) {
                        // 设置不可派单师傅标示
                        resultList.forEach(item => {
                            item.nonDistributeFlag = 2;
                        });
                        initTableViewOfMasterList('distributeList', allMasterList.concat(resultList));
                    } else {
                        initTableViewOfMasterList('distributeList', allMasterList);
                    }

                    /* 渲染工程师地图 */
                    initMapViewOfMasterList('distributeList', allMasterList);
                    updateMasterListTable(distributeInfoJson.masterId, '#mapView, #tableView', allMasterList);
                }, function (data) {
                    layer.msg("获取派单信息失败，请稍后重试。", {"icon": 2});
                });
            }

        }

        /**
         * 初始化服务区域显示
         */
        function initServiceArea(cityId, cb) {
            var cityId = cityId || getters.getCityId();

            if (!cityId) {
                renderServiceArea([]);
                return;
            }

            fetchAreaData(cityId).done(function (data) {
                renderServiceArea(data, cb);
            });
        }

        /**
         * 使用 Select2 初始化工程师下拉框
         */
        function initMasterSelecteBySelect2(data) {
            select2.initRemote({
                el: '#select-master',
                url: MASTER_LIST_URL,
                placeholder: '输入工程师姓名校验是否可派单',
                getParams: function (params) {
                    return {
                        text: params.term,
                        gridId: data.gridId,
                        cityId: infoDataVO.cityId,
                        plat: infoDataVO.plat
                    };
                },
                processor: function (data) {
                    return data.map((item) => {
                        item.id = item.value;
                        return item;
                    });
                },
                formatRepo: formatRepoForMaster
            });
        }

        /**
         *  生成街道地址下拉框列表项
         * @param {Object} data 街道地址数据
         * @returns {string}
         */
        function createFetchSuggestedItemHtmlStr(data) {
            data.district = data.district || '';
            return (
                '<li data-lng="' + data.location.lng +
                '" data-lat="' + data.location.lat +
                '" data-communityid="' + (data.communityId || 999999) +
                '" data-source="' + (data.source || 2) +
                '" data-city="' + data.city +
                '" data-district="' + data.district +
                '" data-name="' + data.name + '">' +
                data.name +
                '<span class="city-district">' +
                data.city + data.district +
                "</span>" +
                "</li>"
            );
        }

        /**
         *  渲染街道列表下拉框
         * @param params 联想参数
         */
        function renderStreetSelect(params) {
            $("#suggestPanel ul").html('<li class="loading tip">加载中</li>');
            $("#servingDuplicateNotice").hide()
            fetchSuggestedStreet(params, function (data) {
                var htmlStr = "";

                if (data.length) {
                    $.each(data, function (index, item) {
                        htmlStr += createFetchSuggestedItemHtmlStr(item);
                    });
                } else {
                    htmlStr += '<li class="non-data tip">无匹配项</li>';
                }

                layer.open({
                    area: ["0", "0"],
                    shade: [0.1, "#fff"],
                    offset: ["100000px", "100000px"],
                    scrollbar: false,
                    zIndex: 888,
                    success: function (layero, index) {
                        $("#layui-layer-shade" + index).on("click", function () {
                            $(layero).find(".layui-layer-close").trigger("click");
                        });
                    },
                    cancel: function () {
                        $("#suggestPanel").hide();
                        clearAddress();
                    },
                });
                $("#suggestPanel ul").html(htmlStr);
                $("#suggestPanel").show();
            });
        }

        /**
         * 校验提交的数据是否合法
         * @param data
         * @returns {boolean}
         */
        function verifySubmitData(data) {
            if (!data.auditStatus) {
                layer.msg("请选择是否同意改派！", {"icon": 2});
                return false;
            }

            if (!data.spuriousStatus) {
                layer.msg("请选择是否虚假改派！", {"icon": 2});
                return false;
            }

            // 如果是【品类错误】且没有选要改的【服务产品】的话
            if (categoryWrongReasonType == infoDataVO.reasonId && !data.productId) {
                layer.msg("请选择服务产品！", {"icon": 2});
                return false;
            }

            // 如果是【地址错误】且没有选择【要改的地址】的话
            if (addressWrongReasonType == infoDataVO.reasonId && (!data.latitude || !data.longitude)) {
                layer.msg("请输入完整用户地址！", {"icon": 2});
                return false;
            }

            // 当【同意改派】 且 没有【选择核实的改派缘由】时
            if (data.auditStatus == 3 && !data.auditReasonId) {
                layer.msg("请选择核实的改派缘由！", {"icon": 2});
                return false;
            }

            // 是否有可以改派的工程师
            let hasRedistributeEngineer = $(".master-options").length >= 1;

            // 可以获取工程师数据，但没有【可选的工程师】时
            let hasChooseEngineer = detailConfig.hasCanFetchRedistributeEngineer && data.auditStatus == 3
            if (hasChooseEngineer && !hasRedistributeEngineer) {
                layer.msg("暂时没有可以改派的工程师，请稍后重试！", {"icon": 2});
                return false;
            }

            // 可以获取工程师数据 且【同意改派】为“是”，但是没有选择工程师，才弹出这个提示
            if (hasChooseEngineer && !data.masterId) {
                layer.msg("请选择工程师！", {"icon": 2});
                return false;
            }

            return true;
        }

        /**
         * 更新弹框标题
         * @param {string} title 标题
         */
        function updateLayerTitle(title) {
            let index = parent.layer.getFrameIndex(window.name);
            parent.layui.$('#layui-layer' + index).find('.layui-layer-title').text(title);
        }

        /**
         * 更新iframe弹框的“名称”及对应的“页面内容”
         *
         * @param params 跳转所携带的参数
         * @param title iframe弹窗的名称
         */
        function openHandleIframe(params, title) {
            // 更新弹窗 title
            updateLayerTitle(title);
            window.location.href = zmnUtils.serializeURL(DETAIL_PAGE_URL, params);
        }

        /**
         * 获取组装后的【改派审核】请求数据
         * @param data
         */
        function getAssemblyData(data) {
            let initParam = {
                countyId: infoDataVO.countyId,
                countyName: infoDataVO.countyName,
                address: infoDataVO.address,
                longitude: infoDataVO.longitude,
                latitude: infoDataVO.latitude,
                streetId: infoDataVO.streetId,
                street: infoDataVO.street,
                streetSource: getters.getStreetSource(),
                servCategId: infoDataVO.servCategId,
                productId: infoDataVO.productId,
                productInfo: infoDataVO.productInfo,
            };

            // 如果 streetId 为null并且缘由是地址错误的话
            if (!data.streetId && infoDataVO.reasonId == addressWrongReasonType) {
                let streetId = $('#communityId').val();

                if (streetId) {
                    //  就把 communityId 赋值给 streetId
                    data.streetId = streetId;
                } else {
                    delete data.streetId;
                }
            }

            // 当【同意改派】为“是” 且 有工程师ID时
            if (data.masterId && data.auditStatus == 3) {
                let optionElement = $("option[class=master-options][value=" + data.masterId + "]")
                data["masterName"] = optionElement.attr("data-master-name")
                data["distributeGrid"] = optionElement.attr("data-distribute-grid")
            } else {
                delete data["masterId"]
            }

            data['orderId'] = infoDataVO.orderId;
            data['workId'] = infoDataVO.workId;
            data['redistributeId'] = infoDataVO.redistributeId;

            // 核实的改派缘由
            data['auditReason'] = $("input[name=auditReasonId][value=" + data['auditReasonId'] + "]").attr("title");

            // 如果是【品类错误】，则添加产品名称和 categId
            if (categoryWrongReasonType == infoDataVO.reasonId) {
                let productElement = $("#productId option[value=" + data.productId + "]");
                data['productInfo'] = productElement.text();
                data['categId'] = productElement.data("categ-id");
            }

            // 如果是【地址错误】
            if (addressWrongReasonType == infoDataVO.reasonId) {
                data['countyName'] = $("#countyId option:selected").text();
                if (!data.countyId || !data.countyName) {
                    delete data.countyId;
                    delete data.countyName;
                }
            }

            return Object.assign(initParam, data);
        }


        /**
         * 获取【上一条/下一条】的改派ID
         * @param dataList 数据
         * @param index 下标
         * @param flagName 判断是否能跳转到指定页面的变量名
         * @param action 执行的动作：【上一条/下一条】
         * @returns {null|*}
         */
        function getNextOrPrevRedistributeId(dataList, index, flagName, action) {

            let redistributeId;

            if (flagName) {
                let dataListClone = Object.assign([], dataList);
                let redistributeObj;

                if (action == 'prev') {
                    // 找到距离当前单子最近的一条，并且满足对应的规则
                    redistributeObj = dataListClone.slice(0, index).reverse().find(value => value[flagName]);
                } else if (action == 'next') {
                    //
                    redistributeObj = dataListClone.slice(++index, dataList.length).find(value => value[flagName]);
                }

                // 没找到，抛出空
                if (!redistributeObj) {
                    return null;
                }

                redistributeId = redistributeObj.redistributeId
            } else {

                if (action == 'prev') {
                    redistributeId = dataList[--index].redistributeId;
                } else if (action == 'next') {
                    redistributeId = dataList[++index].redistributeId;
                }

            }

            return redistributeId;
        }

        /**
         * 跳转到指定的页面
         * @param index 上一条/下一条 的下标
         * @param action
         * @param dataList
         * @param noticeArticle 【上一条/下一条】提示文案
         * @param dialogTitle
         */
        function jumpToDirectPage(index, action, dataList, noticeArticle, dialogTitle) {
            let requestId;
            try {
                // 1.详情 2.审核 3.备注
                switch (type) {
                    case 2: // 审核
                        requestId = getNextOrPrevRedistributeId(dataList, index, 'canAuditFlag', action);
                        break;
                    case 3: // 备注
                        requestId = getNextOrPrevRedistributeId(dataList, index, 'canAddLasterRemarkFlag', action);
                        break;
                    default: // 详情
                        requestId = getNextOrPrevRedistributeId(dataList, index, null, action);
                        break;
                }

                // 如果是改派ID是空，则抛出文案。
                if (requestId == null) {
                    throw noticeArticle;
                }

                openHandleIframe({
                    id: requestId,
                    type: type
                }, dialogTitle)

            } catch (e) {
                console.log(e)
                layer.msg(noticeArticle);
            }
        }

        /**
         * 初始化页面事件
         */
        function initEvent() {

            // 上一页下一页按钮事件
            $(document).on('click', '.work-operation-header .header-left .layui-btn-sm', function () {
                // 初始化数组
                let dataList = window.dataList

                let action = $(this).data('action');
                let text = {
                    prev: '到顶啦',
                    next: '没有更多啦'
                };

                // 长度
                let length = dataList.length;

                // 下标
                let index = dataList.findIndex(e => e.redistributeId == infoDataVO.redistributeId);

                // 上一页
                if (action === 'prev') {
                    if (length && index >= 0) {
                        jumpToDirectPage(index, action, dataList, text[action], iframeTypeNames[type])
                    } else {
                        layer.msg(text[action]);
                    }
                }

                // 下一页
                else if (action === 'next') {
                    if (length && index < (length - 1)) {
                        jumpToDirectPage(index, action, dataList, text[action], iframeTypeNames[type])
                    } else {
                        layer.msg(text[action]);
                    }
                }

            });

            /**
             * 监听 “是否同意改派” 单选按钮
             *  可选值：
             *         2：不同意
             *         3：同意
             */
            form.on("radio(chose-redistribute-audit)", function (data) {

                if (data.value == 2) {
                    $("#auditReasonLabel").removeClass("layui-required");
                    $("#choseRedistributeMaster").addClass("layui-hide");
                    $("#distribute-item").addClass("layui-hide");
                } else if (data.value == 3) {
                    $("#auditReasonLabel").addClass("layui-required");

                    if (detailConfig.hasCanFetchRedistributeEngineer) {
                        $("#choseRedistributeMaster").removeClass("layui-hide");

                        // 如果未初始化才初始化工程师地图
                        if (isInitedEngineerMap) {
                            $("#distribute-item").removeClass("layui-hide");
                            return;
                        }

                        // 渲染派单地图
                        renderDistributeMap(initialDistributeParams[infoDataVO.reasonId])
                    }
                }
            });

            form.on('select(masterSelect)', function (data) {
                var masterId = data.value;

                // 同步更新该工程师在列表中的状态
                updateMasterListTable(masterId, '#mapView, #tableView', allMasterList);
                // 更新语音按钮的状态
                updateVoiceStatus(!masterId);

                $("#distributeGrid").val($(data.elem).find("option:selected").attr('data-distribute-grid'));
            });

            // 录入备注时，必须是【待改派 + （待审核或进行中）】状态才可以进行录入备注。
            $("#last-remark-event").on('click', function () {

                // 打开备注页面
                openHandleIframe({
                    id: infoDataVO.redistributeId,
                    type: 3
                }, '备注')

            });

            // 点击提交
            $('#submitRemark').on('click', function () {

                let lastRemarkValue = $("#lastRemark").val();
                if (!lastRemarkValue) {
                    layer.msg("请输入备注！", {"icon": 2});
                    return false;
                }

                // 提交备注
                addLastRemark({
                    lastRemark: lastRemarkValue
                }).then(function (result) {
                    layer.msg("添加备注成功", {icon: 1, time: 1000}, function () {

                        // 跳转至详情页面
                        openHandleIframe({
                            id: infoDataVO.redistributeId,
                            type: 1
                        }, '详情')

                    });
                }, function (msg) {
                    layer.msg(msg)
                });
            })

            // 点击通话记录事件
            $('#cancel').on('click', function () {
                // 关闭所有弹窗
                parent.layer.closeAll();
            })

            // 点击通话记录事件
            $('.call-log').on('click', function () {
                var omsParams = {
                    orderId: infoDataVO.orderId,
                    workId: infoDataVO.workId
                };
                let url = zmnUtils.serializeURL(OMS_ORDER_CALL_LOG_URL, omsParams);
                operationUtils.openDialog({
                    title: '通话记录',
                    content: url
                });
                return false;
            });

            form.on('submit(jump-action-handle)', function (data) {
                let actionType = $(this).data("action-type");
                openHandleIframe({
                    id: infoDataVO.redistributeId,
                    type: actionType
                }, iframeTypeNames[actionType])
            })


            /**
             * 切换【核实改派缘由】时的事件
             */
            form.on('radio(auditReasonFilter)', function (data) {
                // 【核实缘由ID】是否匹配上了【缘由ID】
                let isNotMatchReasonId = !(infoDataVO.reasonId == data.value);
                $("input[name=spuriousStatus][value=2]").prop("checked", isNotMatchReasonId)
                form.render();
            });

            form.on('submit(check-master)', function (data) {
                let masterId = $('#select-master').val();
                let params = data.field;

                if (!masterId) {
                    zmnUtils.layui.toastError('请先选择要校验的工程师');
                    return false;
                }

                params.masterId = masterId;
                params.distributeWay = $("#distributeWay").val();
                params.categId = $("#productId option[value=" + data.productId + "]").data("categ-id");

                var setCheckResultMessage = function (result, msg) {
                    $('#master-check-msg').removeAttr('class')
                        .addClass(result)
                        .text(msg);
                };

                checkMasterDistributable(params).then(function (masterId, msg) {
                    setCheckResultMessage('success', msg);
                }, function (msg) {
                    setCheckResultMessage('fail', msg);
                });

                return false;
            });

            //tab事件监听
            element.on('tab(tabEvent)', function (data) {
                if (data.index == 0) {
                    $("#distributeList").addClass("layui-show");
                    $("#nonDistributeList").removeClass("layui-show");
                } else if (data.index == 1) {
                    $("#distributeList").removeClass("layui-show");
                    $("#nonDistributeList").addClass("layui-show");
                    if (hasRender == 1) {
                        initTableViewOfMasterList('nonDistributeList', nonGirdMasterList);
                        initMapViewOfMasterList('nonDistributeList', nonGirdMasterList);
                        hasRender = 2;
                    }
                }
            });

            // 可派单工程师双击默认选中
            table.on('radio(tableOfMatserList)', function (obj) {
                var masterId = obj.data.masterId;
                updateMasterSelect(obj.data, false);
                updateVoiceStatus(!masterId);
                $("#distributeGrid").val(obj.data.distributeGrid);
            });

            // 不可派工程师双击默认选中
            table.on('radio(nonTableOfMatserList)', function (obj) {
                var masterId = obj.data.masterId;
                updateNonMasterSelect(obj.data);
                updateVoiceStatus(!masterId);
                $("#distributeGrid").val(obj.data.distributeGrid);
            });

            /* 初始化验证规则 */
            form.verify({
                maxLenTo500: verifyRules.maxLengthFactory(500),
            });

            table.on('rowDouble(tableOfMatserList)', function (obj) {
                var $this = $(obj.tr);
                $this.addClass('current')
                    .siblings('tr')
                    .removeClass('current');

                if (obj.data !== null && obj.data.nonDistributeFlag === undefined) {
                    $this.find('.layui-form-radio .layui-icon').trigger('click');
                }
            });

            table.on('rowDouble(nonTableOfMatserList)', function (obj) {
                var $this = $(obj.tr);
                $this.addClass('current')
                    .siblings('tr')
                    .removeClass('current');

                if (obj.data !== null && obj.data.nonDistributeFlag === undefined) {
                    $this.find('.layui-form-radio .layui-icon').trigger('click');
                }
            });

            // 初始化电话组件
            $('body').on('click', '.btn-netcall', function () {
                var masterId = $(this).data('id');
                makeRadioCall(masterId);
            });

            // 监听网络电话按钮
            form.on('submit(call)', function (data) {
                var masterId = data.field.masterId;
                if (masterId === '') {
                    layer.msg('请选择工程师');
                    return false;
                }
                makeRadioCall(masterId);
                return false;
            });

            $('.v-player').each(function () { //遍历视频列表
                $(this).click(function () { //这个视频被点击后执行
                    let img = $(this).attr('vpath');//获取视频预览图
                    let video = $(this).attr('ipath');//获取视频路径
                    $('.videos').html("<video id=\"video\" poster='" + img + "' src='" + video + "' preload=\"auto\" controls=\"controls\" autoplay=\"autoplay\"></video><i class=\"vclose layui-icon layui-icon-close-fill\"></i>");
                    $('.videos').show();
                });
            });

            $(document).on('click', '.vclose', function () {
                //点击关闭按钮关闭暂停视频
                $('.videos').hide();
                $('.videos').html('');
            })

            /**
             * 打语音电话
             * @param masterId 工程师 id
             */
            function makeRadioCall(masterId) {
                var LOCAL_ITEM_NAME = 'distribute_voice_tips';
                var noTips = window.localStorage.getItem(LOCAL_ITEM_NAME);

                if (noTips === 'off') {
                    zmnUtils.makeCall({masterId: masterId});
                    return;
                }

                //自定页
                layer.open({
                    type: 1,
                    title: '提示',
                    skin: 'modal-distribute', //样式类名
                    closeBtn: 1,
                    anim: 2,
                    area: '425px',
                    shadeClose: true,
                    content: $('#modal-voice-wrapper').html(),
                    success: function ($layer, index) {
                        $layer.find('.layui-btn').attr('lay-filter', 'form-modal');
                        form.render();

                        form.on('submit(form-modal)', function (data) {
                            if (data.field.noTips === 'on') {
                                window.localStorage.setItem(LOCAL_ITEM_NAME, 'off');
                            }
                            layer.close(index);
                            zmnUtils.makeCall({masterId: masterId});

                            return false;
                        });
                    }
                });
            }

            /**
             * 虚假标准
             */
            $("#spuriousStandardTrigger").on('click', function () {
                //弹出层
                layer.open({
                    type: 1,
                    shade: 0.8,
                    offset: 'auto',
                    area: [835 + 'px', 500 + 'px'],
                    shadeClose: true,
                    scrollbar: false,
                    title: "虚假标准", //不显示标题
                    content: $("#spurious-standard").html(),
                    success: function () {
                        $('#spuriousTable').load()
                    },
                });
            });

            /**
             * 工单详情
             */
            $("#orderId").on('click', function () {
                let url = zmnUtils.serializeURL(OMS_BASE_URL + '/work/modify/detail.action', {
                    workId: infoDataVO.workId,
                    orderId: infoDataVO.orderId,
                    operateId: 103 // 工单详情操作
                });

                operationUtils.openDialog({
                    title: '详情',
                    content: url
                });
            })

            /**
             * 监听保存按钮
             */
            form.on('submit(zmn-form-submit)', function (data) {
                if (prohibitSubmit) {
                    layer.msg("请勿重复提交");
                    return;
                }

                // 是否禁止提交
                prohibitSubmit = true;

                // 检查提交的数据是否合法
                let isLegal = verifySubmitData(data.field);
                if (!isLegal) {
                    prohibitSubmit = false;
                    return false;
                }

                // 组装数据
                let assemeblyData = getAssemblyData(data.field);

                $http.lockSave(APPLY_AUDIT_URL, assemeblyData, data.elem).then(function (rsp) {
                    layer.msg('操作成功', {icon: 1, time: 1000}, function () {
                        parent.layer.closeAll();
                        openHandleIframe({
                            id: infoDataVO.redistributeId,
                            type: 1
                        }, '详情')
                    });
                }, (msg) => {
                    layer.msg(msg);
                    prohibitSubmit = false;
                });
                return false;
            });

            // 服务产品下拉框
            form.on("select(select-product)", function (data) {
                let productId = data.value;
                if (productId == "") {
                    $("#servingDuplicateNotice").hide();
                    return;
                }
                let selectedOption = $("#productId option[value=" + productId + "]")
                let categId = selectedOption.data("categ-id");
                let servCategId = selectedOption.data("serv-categ-id");

                // 在途重复校验
                checkServingDuplicateOrder({
                    servCategId: servCategId,
                    categId: categId,
                })

                // 渲染派单地图
                renderDistributeMap({
                    servCategId: servCategId,
                    categId: categId,
                    productId: productId
                })

            });


            // 省份选择下拉框的点击事件处理器
            form.on("select(province)", function (data) {
                handleProvinceSelect(data.value);
            });

            form.on("select(city)", function (data) {
                var cityId = data.value;
                var provinceId = $(data.elem)
                    .find('option[value="' + cityId + '"]')
                    .data("pid");
                if (provinceId) {
                    $("#provinceId").val(provinceId);
                    form.render("select");
                }

                handleCitySelect(cityId);
            });

            // 区县选择下拉框的点击事件处理器
            form.on("select(countyId)", function (data) {
                var countyId = data.value;
                handleCountySelect(countyId);
            });


            // 街道选择下拉框的点击事件处理器
            form.on("select(streetId)", function (data) {
                recreatFuzzyInfo();
            });

            // 精确地址与模糊地址切换
            $("#address-type-exact").on("click", function (e) {
                initFuzzyAddress();
            });

            $("#address-type-fuzzy").on("click", function (e) {
                initExactAddress();
            });

            // 街道输入框输入事件
            (function initStreeInputEvent() {
                var timer = null;
                $("#customerAddress").on("input", function (e) {
                    e.preventDefault();
                    var $this = $(this);

                    clearTimeout(timer);
                    timer = setTimeout(function () {
                        var queryStr = $this.val();
                        var cityName = getSelectedCityName();
                        var cityId = getters.getCityId();
                        renderStreetSelect({
                            queryStr: queryStr,
                            cityName: cityName,
                            cityId: cityId,
                            ak: addOrderWebAk
                        });
                    }, 300);
                });
            })();

            // 街道输入框获取焦点事件
            $("#customerAddress").on("focus", function (e) {
                var $this = $(this);

                var result = checkMapAvailability();
                if (!result.status) {
                    layer.msg(result.msg);
                    $this.blur();
                }
            });

            $("#suggestPanel").on("click", "li:not(.tip)", function () {
                var $li = $(this);

                // 关闭遮罩层
                layer.closeAll();

                var lng = $li.data("lng");
                var lat = $li.data("lat");
                var name = $li.data("name");
                var district = $li.data("district");
                var streetSource = $li.data('source');
                var streetId = $li.data('communityid');

                updateLocationInfo(lng, lat);
                updateStreetInfo(name);
                updateDistrict(district);
                setStreetSource(streetSource);
                setStreetId(streetId);

                // 更新区域list
                setCountyInfo(district, lng, lat, function () {
                });

                // 在途重复校验
                checkServingDuplicateOrder({
                    longitude: lng,
                    latitude: lat,
                })

                // 渲染派单地图
                renderDistributeMap({
                    longitude: lng,
                    latitude: lat,
                    countyId: getters.getCountyId(),
                    streetId: streetId
                })

                $("#suggestPanel").hide();
            });

        }


        /**
         * 初始化页面
         */
        function initPage() {

            /* 初始化服务产品分类 */
            if (categoryWrongReasonType == infoDataVO.reasonId) {
                zmnSelect.selectServCategory('servCategId', {
                    selectedValues: infoDataVO.servCategId,
                    isRadio: true,
                    events: {
                        changed(values) {
                            let value = values[0];
                            if (recentlyServCategId == value) {
                                return;
                            }

                            if (values.length > 0) {
                                /* 渲染产品下拉框 */
                                renderProductSelect(value, null)
                                recentlyServCategId = value;
                                $("#servingDuplicateNotice").hide();
                            } else {
                                /* 清空产品下拉框 */
                                _renderProductSelect([]);
                            }

                        }
                    }
                })

                /* 初始化后台产品下拉框 */
                renderProductSelect(infoDataVO.servCategId, function () {
                    $('#productId').val(infoDataVO.productId);
                })
            }

            // 初始化区域信息
            if (addressWrongReasonType == infoDataVO.reasonId) {
                initServiceArea(null, function () {
                    var countyId = $("#countyId").attr("value");
                    $("#countyId").val(countyId);
                    layui.form.render("select");
                    updateAreaList(countyId);

                    /* 默认值 */
                    $("#countyId").val(infoDataVO.countyId);
                    $("#streetId").val(infoDataVO.streetId);
                    $("#customerAddress").val(infoDataVO.street);
                    $("#longitude").val(infoDataVO.longitude);
                    $("#latitude").val(infoDataVO.latitude);
                    $("#address").val(infoDataVO.address);
                    layui.form.render("select");
                });
            }

            /* 如果改派的缘由是 【品类错误/地址错误】，则进行在途重复校验提醒 */
            if (categoryWrongReasonType == infoDataVO.reasonId || addressWrongReasonType == infoDataVO.reasonId) {
                checkServingDuplicateOrder({
                    productId: infoDataVO.productId,
                    longitude: infoDataVO.longitude,
                    latitude: infoDataVO.latitude,
                })
            }

            // 初始化剪切板控制器
            clipboard.init();

            // 初始化剪切板控制器
            let $clipboard = new ClipboardJS('.btn-phone-copy', {
                text: function (trigger) {
                    let $trigger = $(trigger);
                    let hidMobile = $trigger.data('hidmobile') + '';
                    let targetId = "#" + $trigger.data('target-id');
                    let cryptoMobile = $trigger.data('cryptomobile');

                    console.log("target：", $(targetId).text().indexOf("**"))
                    if ($(targetId).text().indexOf("**") > 0) {
                        return '{"show":"' + hidMobile + '","ciphertext":"' + cryptoMobile + '"}';
                    } else {
                        return $(targetId).text();
                    }
                }
            });

            $clipboard.on('success', function (e) {
                layer.tips('复制成功', e.trigger, {
                    time: 500,
                    tips: [3, '#5FB878']
                })
            });

            // 查看用户手机号
            $('.btn-show-phone').on('click', function () {
                let targetId = $(this).data('target');
                let type = $(this).data('type') || 1; // 1：用户电话  2：预约地址 3：工程师电话
                let indexPhone = $(this).data('index-phone') || 1; // 第几个号码
                let addressType = $(this).data('address-type'); // 地址类型：1.改派地址 2. 订单地址
                let $targetId = $("#" + targetId);

                // 展示出解密后的【订单地址】
                if (targetId == "#hideAddress") {
                    showOrderAddress($targetId);
                    return;
                }

                // 打电话 或者 解密用户电话、预约地址、工程师电话
                showOrCallPhone($targetId, type, indexPhone, addressType)
            });


            // 初始化呼叫电话组件
            (function initCallForCC() {
                if (!top.isCallCenter) {
                    return;
                }

                $('.btn-cc-call').removeClass('layui-hide');

                // 初始化呼叫电话组件
                $('body').on('click', '.btn-cc-call', function () {
                    let type = $(this).data('type'); // 1：用户电话 3：工程师电话
                    let indexPhone = $(this).data('index-phone') || null; // 第几个号码
                    showOrCallPhone(null, type, indexPhone, null)
                });
            }());

            // 初始化图片预览器
            previewer.initTextList('.container-images');
        }


        function init() {
            // 初始化页面
            initPage();

            // 初始化事件
            initEvent();
        }

        init();
        exports('oms_redistribute_detail');
    });